﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Script.Serialization;
using WeBlog.Helpers;
using WeBlog.Models;

namespace WeBlog.Services
{
    public static class SiteManager
    {
        private const string SettingsFileName = "Settings.txt";

        static SiteManager()
        {
            var directory = FileManager.SiteDirectory;
            if (directory.Exists) return;
            directory.Create();
			_allConfigItems = null;
        }                

        public static void Save(SiteConfiguration configuration)
        {
			var path = Path.Combine(FileManager.SiteDirectory.FullName, configuration.Id.ToString());
            Directory.CreateDirectory(path);
            var serializer = new JavaScriptSerializer();
            var content = serializer.Serialize(configuration);
            var file = Path.Combine(path, SettingsFileName);
            File.WriteAllText(file, content);
			_allConfigItems = null;
        }

        public static SiteConfiguration Load(string name)
        {
            var configurations = FindAll()
					.Where(x => x.Name.Equals(name))
					.ToList();
            return configurations.First();
        }

        public static SiteConfiguration CurrentConfiguration
        {
            get
            {				
				var matches = FindCurrent().ToList();
				return !matches.Any() ? new SiteConfiguration { HostHeaderValues = GetBaseUrl() } : matches.First();
            }
        }

        public static bool Any()
        {
            if (FileManager.SiteDirectory.Exists == false) return false;

            foreach (var siteFolder in FileManager.SiteDirectory.GetDirectories())
            {
                var path = Path.Combine(siteFolder.FullName, SettingsFileName);
                if (File.Exists(path)) return true;
            }

            return false;
        }

		public static bool IsCurrentSiteConfigured()
		{
			return FindCurrent().Count() != 0;
		}

		public static string GetBaseUrl()
		{
			System.Web.HttpContext context = System.Web.HttpContext.Current;
			if (context != null)
			{
				Uri url = context.Request.Url;
				return string.Format(@"http://{0}{1}",
					url.Host,
					url.IsDefaultPort ? "" : string.Format(":{0}", url.Port));
			}
			return "http://localhost";
		}

		private static IEnumerable<SiteConfiguration> FindAll()
        {
			if (_allConfigItems == null)
			{
				_allConfigItems = EnumerateAllFromDisk()
					.ToList();
			}
			return _allConfigItems;
        }

		private static IEnumerable<SiteConfiguration> FindCurrent()
		{
			string currentUrl = GetBaseUrl();
			return FindAll()
				.Where(x => x.FindHostHeaders()
					.Any(h => h.Equals(currentUrl, StringComparison.CurrentCultureIgnoreCase)));
		}

		private static IEnumerable<SiteConfiguration> EnumerateAllFromDisk()
		{
			var serializer = new JavaScriptSerializer();

			foreach (var siteFolder in FileManager.SiteDirectory.GetDirectories())
			{
				var path = Path.Combine(siteFolder.FullName, SettingsFileName);
			    if (!File.Exists(path)) continue;
			    var content = File.ReadAllText(path);
			    var config = serializer.Deserialize(content, typeof(SiteConfiguration));
			    yield return (config as SiteConfiguration);
			}
		}

		private static IEnumerable<SiteConfiguration> _allConfigItems;
	}
}
